﻿/**
 * Crowd
 *
 * @author		Allen Chou
 * @version		1.0.0 (last update: Jan 7 2009)
 * @link        http://cjcat.blogspot.com
 * @link		http://cjcat2266.deviantart.com
 */

package idv.cjcat.utils.crowd {
	import flash.events.Event;

	/**
	 * The <code>Crowd</code> class manages/manipulates a group of objects as a whole using a single common function.
	 * 
	 * <p>
	 * Each <code>Entity</code> object holds a reference to an object and a reference of a parameter object. 
	 * The parameter object can be of any type, be it Number, int, Array, or Vector. 
	 * The <code>func</code> property of a <code>Crowd</code> should refer to a function with signature <code>func(entity:Entity):void</code>. 
	 * Each time the <code>update</code> method is called, every entity in the crowd is passed as the function's only parameter. 
	 * How each entity is manipulated is defined in this function.
	 * </p>
	 */
	public class Crowd {
		
		/**
		 * The manipulator function.
		 */
		public var func:Function;
		
		private var _entities:Vector.<Entity> = new Vector.<Entity>();
		
		/**
		 * Creates a crowd.
		 * @param	func  The manipulator function
		 */
		public function Crowd(func:Function) {
			this.func = func;
		}
		
		/**
		 * Adds an entity to the crowd.
		 * @param	entity  The entity.
		 */
		public function add(entity:Entity):void {
			if (_entities.indexOf(entity) < 0) _entities.push(entity);
		}
		
		/**
		 * Removes an entity from the crowd.
		 * @param	entity  The entity.
		 */
		public function remove(entity:Entity):void {
			var index:Number = _entities.indexOf(entity);
			if (index >= 0) _entities.splice(index, 1);
		}
		
		/**
		 * Removes all entities from the crowd.
		 */
		public function clear():void {
			_entities.length = 0;
		}
		
		/**
		 * Call this method to pass every entity to the manipulator function.
		 * <p>This method can be used as an event listener.</p>
		 * @param	e
		 */
		public function update(e:Event = null):void {
			for each (var entity:Entity in _entities) func(entity);
		}
		
	}
}